<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20" style="margin-bottom: 18px">
        <!-- 搜索区 -->
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table stripe :data="usersList" borde>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="账号"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- 使用作用域插槽渲染了状态 如果制定了作用域插槽父级的prop='xx'属性会被覆盖，可以删除prop -->
          <template slot-scope="props">
            <el-switch
              v-model="props.row.mg_state"
              @change="userStateChanged(props.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="props">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="editForm(props.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="removeUserById(props.row.id)"
            ></el-button>
            <!-- 包裹了Tooltip 文字提示 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="small"
                @click="setRole(props.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户模态框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="resetForm"
    >
      <!-- 主内容区 -->
      <el-form
        :model="addForm"
        :rules="rulesForm"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="addForm.password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户模态框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editFormClosed"
    >
      <el-form
        :model="editFormData"
        ref="editFormRef"
        :rules="editFormRules"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editFormData.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editFormData.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editFormData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 角色分配框 -->
    <el-dialog title="分配角色" :visible.sync="roleVisible" width="50%">
      <div>
        <p>当前的用户: {{ userInfo.username }}</p>
        <p>当前的角色: {{ userInfo.role_name }}</p>
        <p>
          分配新角色:
          <template>
            <el-select v-model="selectedRoleId" clearable placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </template>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    const checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号码的规则
    const checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 用来查询用户信息的请求参数
      queryInfo: {
        query: '', // 搜索关键字
        pagenum: 1, // 当前页数
        pagesize: 2 // 每页显示多少条
      },
      usersList: [], // 保存请求回来的用户列表数据
      total: 0, // 总页数
      dialogVisible: false, // 控制模态框是否显示
      // 添加表单
      addForm: {
        username: '',
        passwold: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证规则
      rulesForm: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入喵喵', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑表单模态框是否展示
      editDialogVisible: false,
      // 编辑表单数据
      editFormData: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      // 编辑表单的验证规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 分配角色框显示否
      roleVisible: false,
      // 保存正在操作的那个用户信息
      userInfo: {},
      // 保存所有的角色信息
      rolesList: [],
      // 保存用户选中的角色id
      selectedRoleId: ''
    }
  },
  // 在实例创建完成后被立即调用
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      // 网络请求获取用户列表
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      // 如果状态码不等于200 获取失败
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      // 如果返回状态正常，将请求的数据保存在data()中
      this.usersList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // 把每页多少条的值 赋值给data()里的值后重新发送请求
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      // 把当前是哪页的值 赋值给data()里的值后重新发送请求
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    async userStateChanged(data) {
      const { data: res } = await this.$http.put(
        `users/${data.id}/state/${data.mg_state}`
      )
      if (res.meta.status !== 200) return this.$message.error('设置状态失败')
      this.$message.success('设置状态成功')
    },
    resetForm() {
      // 对整个表单进行重置
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        // 如果失败后直接返回
        if (!valid) return
        // 如果成功发送网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        // 创建成功
        if (res.meta.status === 201) {
          this.$message.success('创建成功')
        } else {
          this.$message.errot('创建失败')
        }
        // 关闭制模态
        this.dialogVisible = false
        // 重新请求最新的数据
        this.getUserList()
      })
    },
    async editForm(id) {
      // 点击编辑按钮触发事件 展示模态框
      this.editDialogVisible = true
      // 根据传入的形参 当前用户id的查询用户信息
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      // 如果状态等于200 返回成功 表单回填
      if (res.meta.status === 200) {
        this.editFormData.username = res.data.username
        this.editFormData.email = res.data.email
        this.editFormData.mobile = res.data.mobile
        this.editFormData.id = res.data.id
      } else {
        this.$message.erro('获取用户失败')
      }
    },
    editFormClosed() {
      // 对整个表单进行重置
      this.$refs.editFormRef.resetFields()
    },
    editUser() {
      // 用户点击修改表单中的确定按钮之后，验证表单数据
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          // 验证通过后发送网络请求修改用户
          const { data: res } = await this.$http.put(
            'users/' + this.editFormData.id,
            {
              email: this.editFormData.email,
              mobile: this.editFormData.mobile
            }
          )
          // console.log(res)
          // 状态码200说明请求成功
          if (res.meta.status === 200) {
            this.$message.success('更新成功')
            // 隐藏模态框
            this.editDialogVisible = false
            // 更新数据和页面
            this.getUserList()
          }
        } else {
          this.$message.error('更新用户失败')
        }
      })
    },
    async removeUserById(id) {
      // 根据id删除对应的用户
      const isConfirm = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      // 如果点击确认返回 "confirm"
      // 如果点击取消返回"cancel" 取消必须使用.catah()捕获错误，要不会报错
      // console.log(isConfirm)
      if (isConfirm === 'cancel') return this.$message.info('取消了删除')
      const { data: res } = await this.$http.delete('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功了')
      this.getUserList()
    },
    async setRole(data) {
      // console.log(data)
      this.userInfo = data
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.rolesList = res.data
      // console.log(res)
      this.roleVisible = true
    },
    // 保存分配的用户角色
    async saveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择')
      }
      const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      // console.log(res)
      if(res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功')
      this.getUserList()
      this.roleVisible = false
    }
  }
}
</script>

<style lang="less" scoped></style>
